package com.cryptooj.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cryptooj.project.common.ErrorCode;
import com.cryptooj.project.constant.CommonConstant;
import com.cryptooj.project.exception.BusinessException;
import com.cryptooj.project.judge.JudgeService;
import com.cryptooj.project.mapper.QuestionSubmitMapper;
import com.cryptooj.project.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.cryptooj.project.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.cryptooj.project.model.entity.Question;
import com.cryptooj.project.model.entity.QuestionSubmit;
import com.cryptooj.project.model.entity.User;
import com.cryptooj.project.model.enums.QuestionSubmitLanguageEnum;
import com.cryptooj.project.model.enums.QuestionSubmitStatusEnum;
import com.cryptooj.project.model.vo.QuestionSubmitVO;
import com.cryptooj.project.service.QuestionService;
import com.cryptooj.project.service.QuestionSubmitService;
import com.cryptooj.project.service.UserService;
import com.cryptooj.project.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 *  题目作答提交service的实现类
 * */
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper,QuestionSubmit> implements QuestionSubmitService{

    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;

    @Resource
    @Lazy // 懒加载
    private JudgeService judgeService;

    /**
     * 提交题目
     */
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        // 校验编程语言是否合法
        String language = questionSubmitAddRequest.getLanguage();
        QuestionSubmitLanguageEnum languageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if (languageEnum == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言错误");
        }
        long questionId = questionSubmitAddRequest.getQuestionId();
        // 判断实体是否存在，根据类别获取实体
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "作答的题目对象不存在");
        }
        // 尝试提交题目作答
        long userId = loginUser.getId();
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setLanguage(language);
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        questionSubmit.setJudgeInfo("{}");
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setUserId(userId);
        boolean save = this.save(questionSubmit);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"数据插入失败！");
        }
        Long questionSubmitId = questionSubmit.getId();
        // 用户提交作答成功后，执行判题服务
        CompletableFuture.runAsync(() ->{
            judgeService.doJudge(questionSubmitId);
        });
        return questionSubmitId;
    }

    /**
     *  获取查询条件包装类
     *  （根据前端传来的请求对象，得到MyBatis支持的QueryWrapper)
     *  （即根据前端的查询条件转 SQL ）
     * */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if(questionSubmitQueryRequest == null){
            return queryWrapper;
        }
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();
        // 拼接查询条件
        queryWrapper.eq(StringUtils.isNotBlank(language),"language",language);
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status)!=null,"status",status);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId),"questionId",questionId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId),"userId",userId);
        queryWrapper.eq("isDelete",false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),sortOrder.equals(CommonConstant.SORT_ORDER_ASC),sortField);
        return queryWrapper;
    }

    /**
     *  获取题目作答提交后的结果VO
     * */
    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVO(questionSubmit);
        long userId = loginUser.getId();
        // 脱敏: 若当前请求作答结果的用户既不是提交作答的用户，也不是管理员，则不返回作答的代码
        if(userId != questionSubmit.getUserId() && !userService.isAdmin(loginUser)){
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
    }

    /**
     *  获取题目作答提交后的分页后的结果VO
     *  (实现方法：从Page对象中取出List，遍历List中的对象转换为VO，构造出VOList，传入新的Page）
     * */
    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(
                questionSubmitPage.getCurrent(),
                questionSubmitPage.getSize(),
                questionSubmitPage.getTotal());
        if(CollectionUtils.isEmpty(questionSubmitList)){
            return questionSubmitVOPage;
        }
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList
                .stream()
                .map(questionSubmit -> getQuestionSubmitVO(questionSubmit, loginUser))
                .collect(Collectors.toList());
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }
}
